<script setup>
import { ref, reactive, onMounted } from 'vue';
import {getAdelist,DelAddress,UpdateAdd } from "@/api/addres";
import {AddAddress} from "@/api/addres";
import pca from '@/assets/pca-code.json'; // 假设这是一个JSON文件，包含地址数据
import {useAddressStore, useUserStore} from "@/stores";
import Footer from "@/components/Footer.vue";

//使用用户仓库
const userStore=useUserStore()
const addressStore=useAddressStore()
// 表格数据
const addressData = ref([]);
// 用于标记每行是否处于编辑状态
const addressEdit = ref([]);



// 地址级联选择器的数据
const pcaOptions = ref(pca);
// 地址级联选择器的属性绑定
const addressProps = reactive({
  label: 'name',
  children: 'children',
  value: 'code'
});

// 组件挂载后加载地址数据
onMounted(() => {
  // 如果有实际的数据加载逻辑，取消注释并实现
  loadAddressData()
  // 初始化数据和编辑状态
  const initData = [{ adname: '', adphone: '', adpca: '', addetail: '', adisdefault: '0' }];
  addressData.value = initData;
  addressEdit.value = initData.map(() => false);

});

// 加载地址数据的函数
const loadAddressData= async ()=> {
    const res = await getAdelist(userStore.userid);
      // 假设res.data是一个包含地址数据的数组
      addressData.value = res.data.data;
      addressStore.DefautAddress=res.data.data

}

// 新增地址的函数
function addAddress() {
  const newRow = {
    adname: '',
    adphone: '',
    adpca: '',
    addetail: '',
    adisdefault: '0'
  };
  addressData.value.push(newRow);
  // 设置新增行的可编辑状态
  addressEdit.value.push(true);
  // 遍历addressEdit数组，将其他所有行的编辑状态设置为false
  for (let i = 0; i < addressEdit.value.length; i++) {
    if (i !== addressData.value.length - 1) {
      addressEdit.value[i] = false;
    }
  }
  // 将增行的可编辑状态设置为true
  addressEdit.value[addressEdit.value.length+1]=true
}

// 筛选出adisdefault为1的对象
const filterAdside=(addressList)=>{
  // 筛选出adisdefault为1的对象并alert
  // addressList.value.forEach((address, index) => {
  //   if (address.adisdefault === '1') {
  //     addressStore.DefautAddress=addressList[index]
  //   }
  // })
  addressStore.DefautAddress=addressList
}

//更新地址操作
// 保存和确定修改的切换
let isOk=ref(true)
const UpdateAddress=async (index,id)=>{
  // 构建传参数据
  const Address = {
    id:id,
    userid: userStore.userid,
    adname: addressData.value[index].adname,
    adphone: addressData.value[index].adphone,
    adpca: addressData.value[index].adpca,
    addetail: addressData.value[index].addetail,
    adisdefault:addressData.value[index].adisdefault, // 根据实际情况转换默认地址的表示方法
  };
  //更新按钮与保存转换
  isOk=true
  addressEdit.value[index] = false;
  // 发起请求传参
  const res=await UpdateAdd(Address)
  ElMessage.success('地址修改成功')
}
// 编辑地址的函数
function editAddress(index) {
  //更新按钮与保存转换
  isOk=false
  addressEdit.value[index] = true;
}

// 保存地址的函数 地址添加
const saveAddress=async (index)=> {
  // 从当前行获取参数
  const newAddress = {
    userid: userStore.userid,
    adname: addressData.value[index].adname,
    adphone: addressData.value[index].adphone,
    adpca: addressData.value[index].adpca,
    addetail: addressData.value[index].addetail,
    adisdefault:addressData.value[index].adisdefault, // 根据实际情况转换默认地址的表示方法
  };
  // 这里可以添加保存逻辑，比如通过axios发送到后端
  const res=await AddAddress(newAddress)
  ElMessage.success('地址添加成功')
  addressEdit.value[index] = false;
  loadAddressData()
}

// 删除地址的函数
const deleteAddress = async (id) => {
  // 使用 Element UI 的 ElMessageBox 进行确认
  try {
    const isConfirm = await ElMessageBox.confirm(
        '此操作将永久删除该地址，是否继续？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    );
    if (isConfirm) {
      // 如果用户确认，发起请求删除地址,
        const res = await DelAddress(id);
        ElMessage.success('删除成功');
        loadAddressData(); // 重新加载地址数据
      }
  } catch (error) {
    console.error('Error deleting address:', error);
    ElMessage.error('删除操作异常');
  }
};

// 处理地址选择器变化的函数
function handleAddressNode(index, value) {
  // value为数组，取最后一级作为选中的地址编码
  addressData.value[index].adpca = value[value.length - 1];
}

// 修改默认地址的函数
function changetest(index, val) {
  // 这里实现切换默认地址的逻辑
  // 例如，将其他所有行的adisdefault设置为'0'，当前行设置为'1'
  addressData.value.forEach((row, i) => {
    if (i === index) {
      row.adisdefault = val;
    } else {
      row.adisdefault = '0';
    }
  });
}
</script>

<template>
  <div class="body" style="padding: 45px; width: 100%">
    <el-card class="box-card" shadow="always" style="width: 93%">
      <template #header>
        <div class="card-header" style="text-align: left">
          <span>管理地址</span>
          <el-button class="button" type="text" @click="addAddress">新增</el-button>
        </div>
      </template>
       <el-table
          :data="addressData"
          style="width: 100%">
        <el-table-column type="index"></el-table-column>
        <el-table-column
            prop="adname"
            label="收货人"
            width="150">
          <template #default="scope">
            <el-input
                :disabled="!addressEdit[scope.$index]"
                size="medium"
                v-model="scope.row.adname"></el-input>
          </template>
        </el-table-column>
         <el-table-column
             prop="adphone"
             label="联系方式"
             width="150">
           <template #default="scope">
           <el-input
               :disabled="!addressEdit[scope.$index]"
               size="medium"
               v-model="scope.row.adphone"></el-input>
           </template>
         </el-table-column>
        <!-- 其他列... -->
        <el-table-column
            prop="adpca"
            label="收货地址"
            width="250"
            align="center">
          <template #default="scope">
            <el-cascader
                v-model="scope.row.adpca"
                :options="pcaOptions"
                :props="addressProps"
                placeholder="请选择"
                :disabled="!addressEdit[scope.$index]"
                @change="handleAddressNode(scope.$index, $event)">
            </el-cascader>
          </template>
        </el-table-column>
        <el-table-column prop="addetail" label="详细地址" width="200">
          <template #default="scope">
            <el-input
                :disabled="!addressEdit[scope.$index]"
                size="medium"
                v-model="scope.row.addetail"></el-input>
          </template>
        </el-table-column>
        <el-table-column
            prop="adisdefault"
            label="默认地址"
            width="120">
          <template #default="scope">
            <el-checkbox
                :disabled="!addressEdit[scope.$index]"
                v-model="scope.row.adisdefault"
                :true-label="1"
                :false-label="0"
                @change="changetest(scope.$index, scope.row.adisdefault)">
              设为默认
            </el-checkbox>
          </template>
        </el-table-column>
        <el-table-column
            label="操作"
            align="center"
            width="270">
          <template #default="scope">
            <el-button
                size="small"
                icon="el-icon-edit"
                @click="editAddress(scope.$index)">编辑</el-button>
            <el-button
                v-if="isOk"
                size="small"
                icon="el-icon-check"
                @click="saveAddress(scope.$index)">保存</el-button>
            <el-button
                v-else
                size="small"
                icon="el-icon-check"
                @click="UpdateAddress(scope.$index,scope.row.id)">保存修改</el-button>
            <el-button
                size="small"
                icon="el-icon-check"
                @click="deleteAddress(scope.row.id)">删除</el-button>
            <el-popconfirm
                confirmButtonText='好的'
                cancelButtonText='不用了'
                icon="el-icon-info"
                title="确定删除该地址？"
                @confirm="deleteAddress(scope.$index)">
              <el-button
                  type="warning"
                  icon="el-icon-delete">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>

  <div class="footer">
    <Footer></Footer>
  </div>

</template>



<style scoped>
.body{
}
.footer{
  position: absolute;
  bottom: 0;
  width: 100%; /* 或者设置为与内容区域相同的宽度 */
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
